package dao;

import pojo.Book;
import utils.JDBCUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDAO {

    private static final String TABLE_NAME = "tb_books";

    // 添加图书
    public static void addBook(Book book) throws SQLException {
        String sql = "INSERT INTO " + TABLE_NAME + " (title, author, isbn, cover_image_url, price) VALUES (?, ?, ?, ?, ?)";
        JDBCUtils.execute(sql, book.getTitle(), book.getAuthor(), book.getIsbn(),
                book.getCoverImageUrl(), book.getPrice());
    }

    // 删除图书
    public static void deleteBook(int bookId) throws SQLException {
        String sql = "DELETE FROM " + TABLE_NAME + " WHERE book_id = ?";
        JDBCUtils.execute(sql, bookId);
    }

    // 更新图书信息
    public static void updateBook(Book book) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME + " SET title = ?, author = ?, isbn = ?, cover_image_url = ?, price = ? WHERE book_id = ?";
        JDBCUtils.execute(sql, book.getTitle(), book.getAuthor(), book.getIsbn(),
                book.getCoverImageUrl(), book.getPrice(), book.getBookId());
    }

    // 获取所有图书
    public static List<Book> getAllBooks() throws SQLException {
        List<Book> books = new ArrayList<>();
        String sql = "SELECT * FROM " + TABLE_NAME;
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql);
        while (resultSet.next()) {
            Book book = createBookFromResultSet(resultSet);
            books.add(book);
        }
        return books;
    }

    // 根据图书ID获取图书信息
    public static Book getBookById(int bookId) throws SQLException {
        String sql = "SELECT * FROM " + TABLE_NAME + " WHERE book_id = ?";
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql, bookId);
        if (resultSet.next()) {
            return createBookFromResultSet(resultSet);
        }
        return null;
    }

    // 创建 Book 对象从 ResultSet 中
    private static Book createBookFromResultSet(ResultSet resultSet) throws SQLException {
        Book book = new Book();
        book.setBookId(resultSet.getInt("book_id"));
        book.setTitle(resultSet.getString("title"));
        book.setAuthor(resultSet.getString("author"));
        book.setIsbn(resultSet.getString("isbn"));
        book.setCoverImageUrl(resultSet.getString("cover_image_url"));
        book.setPrice(resultSet.getDouble("price"));
        return book;
    }
}
